package com.yangtzeu.jwc.activity;

import java.util.ArrayList;
import java.util.List;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.os.SystemClock;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.LinearLayout.LayoutParams;

import com.yangtzeu.jwc.app.MyApplication;
import com.yangtzeu.jwc.business.AppBusiness;
import com.yangtzeu.jwc.businessservice.BusinessHttpCallBack;
import com.yangtzeu.jwc.businessservice.impl.LoaderBusiness;
import com.yangtzeu.jwc.businessservice.impl.StudentServiceImpl;
import com.yangtzeu.jwc.customview.CustomeProgressDialog;
import com.yangtzeu.jwc.utils.Common;
import com.yangtzeu.jwc.utils.ConfirmDialog;
import com.yangtzeu.jwc.utils.G;
import com.zhangdi.jwc.R;
import com.zjsx.lib.utils.T;

public class UserActivity extends BaseActivity implements OnPageChangeListener {
    private TextView tv_userid;
    private TextView tv_usersex;
    private TextView tv_username;
    private TextView tv_userclass;
    private TextView tv_usernumber;
    private ImageView iv_userPhoto;
    private RelativeLayout rl_changepassword;
    private RelativeLayout rl_logout;

    private static final int SHOWPROGRESSDIALOG = 0;
    private static final int DISMISSDIALOG = 1;
    private static final int LOADINGFAILED = 2;
    private static final int LOADINGUSERINFOFINISHED = 3;

    private List<ImageView> imageViewList;
    private LinearLayout llPoints;
    private String[] imageDescriptions;
    private int previousSelectPosition = 0;
    private ViewPager mViewPager;
    private boolean isLoop = true;

    private ProgressDialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void setView() {
        // TODO Auto-generated method stub
        super.setView();
        setContentView(R.layout.activity_user);
    }

    @Override
    public void initData() {
        // TODO Auto-generated method stub
        super.initData();
    }

    @Override
    public void initView() {
        // TODO Auto-generated method stub
        super.initView();
        tv_username = (TextView) this.findViewById(R.id.username);
        tv_usersex = (TextView) this.findViewById(R.id.usersex);
        tv_usernumber = (TextView) this.findViewById(R.id.usernumber);
        tv_userclass = (TextView) this.findViewById(R.id.userclass);
        tv_userid = (TextView) this.findViewById(R.id.userid);
        iv_userPhoto = (ImageView) this.findViewById(R.id.userPhoto);
        rl_changepassword = (RelativeLayout) this.findViewById(R.id.rl_changepassword);
        rl_changepassword.setOnClickListener(this);
        rl_logout = (RelativeLayout) this.findViewById(R.id.rl_logout);
        rl_logout.setOnClickListener(this);
        // 自动切换页面功能
        new Thread(new Runnable() {

            @Override
            public void run() {
                while (isLoop) {
                    SystemClock.sleep(2000);
                    handler.sendEmptyMessage(999);
                }
            }
        }).start();

        mViewPager = (ViewPager) this.findViewById(R.id.viewpager);
        llPoints = (LinearLayout) this.findViewById(R.id.ll_points);
        int width = Common.getScreen(this)[0];
        int mWidth = Px2Dp(this, width);
        int height = Px2Dp(this, (width * 618) / 1000);
        mViewPager.setLayoutParams(new RelativeLayout.LayoutParams(mWidth, height));
        prepareData();

        ViewPagerAdapter adapter = new ViewPagerAdapter();
        mViewPager.setAdapter(adapter);
        mViewPager.setOnPageChangeListener(this);

        llPoints.getChildAt(previousSelectPosition).setEnabled(true);

        /**
         * 2147483647 / 2 = 1073741820 - 1
         */
        int n = Integer.MAX_VALUE / 2 % imageViewList.size();
        int itemPosition = Integer.MAX_VALUE / 2 - n;

        mViewPager.setCurrentItem(itemPosition);
        initUserTab();
    }

    @Override
    public void initListener() {
        // TODO Auto-generated method stub
        super.initListener();
    }

    @Override
    public void handleMsg(Message msg) {
        // TODO Auto-generated method stub
        super.handleMsg(msg);
        switch (msg.what) {
            case SHOWPROGRESSDIALOG:
                T.showShort(this, "加载");
                dialog = CustomeProgressDialog.show(this, "正在加载。。。");
                break;
            case DISMISSDIALOG:
                if (dialog != null) {
                    // dialog.dismiss();
                }
                break;
            case LOADINGFAILED:
                String failureMsg = msg.getData().getString("msg");
                MyApplication.getInstance().showShortToast(failureMsg);
                break;
            case LOADINGUSERINFOFINISHED:
                loadUserInfo();
                LoaderBusiness.loadImage(MainActivity.student.getSphoto(), iv_userPhoto);
                break;
            case 999:
                mViewPager.setCurrentItem(mViewPager.getCurrentItem() + 1);
                break;
            default:
                break;
        }

    }

    private void prepareData() {
        imageViewList = new ArrayList<ImageView>();
        int[] imageResIDs = getImageResIDs();
        ImageView iv;
        View view;
        for (int i = 0; i < imageResIDs.length; i++) {
            iv = new ImageView(this);
            iv.setBackgroundResource(imageResIDs[i]);
            imageViewList.add(iv);

            // 添加点view对象
            view = new View(this);
            view.setBackgroundDrawable(getResources().getDrawable(R.drawable.point_background));
            LayoutParams lp = new LayoutParams(5, 5);
            lp.leftMargin = 10;
            view.setLayoutParams(lp);
            view.setEnabled(false);
            llPoints.addView(view);
        }
    }

    private int[] getImageResIDs() {
        return new int[]{R.drawable.yangtzeu_pic1, R.drawable.yangtzeu_pic2, R.drawable.yangtzeu_pic3, R.drawable.yangtzeu_pic4, R.drawable.yangtzeu_pic5, R.drawable.yangtzeu_pic6,};
    }

    class ViewPagerAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return Integer.MAX_VALUE;
        }

        /**
         * 判断出去的view是否等于进来的view 如果为true直接复用
         */
        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }

        /**
         * 销毁预加载以外的view对象, 会把需要销毁的对象的索引位置传进来就是position
         */
        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView(imageViewList.get(position % imageViewList.size()));
        }

        /**
         * 创建一个view
         */
        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            container.addView(imageViewList.get(position % imageViewList.size()));
            return imageViewList.get(position % imageViewList.size());
        }
    }

    @Override
    public void onPageScrollStateChanged(int arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onPageSelected(int position) {
        // 切换选中的点
        llPoints.getChildAt(previousSelectPosition).setEnabled(false); // 把前一个点置为normal状态
        llPoints.getChildAt(position % imageViewList.size()).setEnabled(true); // 把当前选中的position对应的点置为enabled状态
        previousSelectPosition = position % imageViewList.size();
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        isLoop = false;
    }

    private void showLoginWindow() {
        Intent intent = new Intent();
        intent.setClass(this, LoginActivity.class);
        startActivityForResult(intent, 0);
    }

    /* 初始化用户信息界面和开始获取用户信息 */
    private void initUserTab() {
        getUserInfo();
        loadUserInfo();
    }

    /* 加载用户信息到tab */
    private void loadUserInfo() {
        tv_username.setText(MainActivity.student.getSname());
        tv_usersex.setText(MainActivity.student.getSsex());
        tv_usernumber.setText(MainActivity.student.getSno());
        tv_userclass.setText(MainActivity.student.getSclass());
        tv_userid.setText(MainActivity.student.getSjid());
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 0) {
            if (MainActivity.student != null) {
                initUserTab();
            }
        }
    }

    /**
     * 得到用户信息
     */
    private void getUserInfo() {
        if ("info".equals(MainActivity.student.type))
            return;
        StudentServiceImpl.getInstance().getStudentInfo(new BusinessHttpCallBack() {
            @Override
            public void onFailure(byte[] responseBody, String failuremsg, boolean isNoticeDialog) {
                Message msg = handler.obtainMessage();
                msg.what = LOADINGFAILED;
                msg.getData().putString("msg", failuremsg);
                handler.sendMessage(msg);
            }

            @Override
            public void onSuccess(byte[] responseBody, String successMsg, boolean isNoticeDialog, Object obj) {
                handler.sendEmptyMessage(LOADINGUSERINFOFINISHED);
                AppBusiness ab = new AppBusiness(UserActivity.this);
                ab.login();
            }

        });
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.rl_changepassword:
                if (MainActivity.student != null) {
                    Intent itt = new Intent();
                    itt.setClass(this, ChangePasswordActivity.class);
                    startActivity(itt);
                } else {
                    showLoginWindow();
                }
                break;
            case R.id.rl_logout:
                if (MainActivity.student == null) {
                    Toast.makeText(UserActivity.this, "还没有登录", Toast.LENGTH_SHORT).show();
                } else {
                    if (ConfirmDialog.show(UserActivity.this, "注销", "注销将清除相关数据及保存的密码，确定吗？")) {
                        MainActivity.student = null;
                        StudentServiceImpl.getInstance().clearStudent(UserActivity.this);
                        Intent itt = new Intent();
                        itt.setAction(G.BROADCAST_LOGOUT);
                        sendBroadcast(itt);
                        this.finish();
                    }
                }
                break;
            default:
                break;
        }
    }

    public int Px2Dp(Context context, float px) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (px / scale + 0.5f);
    }

}
